import os

userconf = './conf/users'
appconf = './conf/apps'


class Dictionary:
    dictpath = './dict/dict.json'
    def __init__(self):
        f = open(Dictionary.dictpath, 'r', encoding='utf-8')
        self.dictionary = eval(f.read())
        f.close()

    def add(self, key):
        if key not in self.dictionary:
            self.dictionary[key] = len(self.dictionary)

    def writeBack(self):
        f = open(Dictionary.dictpath, 'w', encoding='utf-8')
        f.write(str(self.dictionary))
        f.close()

def genDict(dictionary):
    l = os.listdir('.')
    for x in l:
        if 'app' in x and os.path.isdir(x):
            p = os.path.join(x, "p")
            if os.path.exists(p):
                file = open(p, 'rb')
                text = file.read().decode('utf-8')
                file.close()
                l = text.splitlines()
                for x in l:
                    def pick(x):
                        i = 0
                        while i < len(x) and ('a' <= x[i] <= 'z' or 'A' <= x[i] <= 'Z'):
                            i += 1
                        if i > 0:
                            return x[:i], x[i:]
                        return x[i], x[i+1:]
                    while len(x):
                        c, x = pick(x)
                        dictionary.add(c)
                    

                


def pick(s):
    i = 0
    while i < len(s):
        if s[i] in '"[]{}\'\\':
            s = s[:i] + '\\' + s[i:]
            i += 1
        i += 1
    return s


def deal(path):
    if os.path.exists(path+'.pct'):
        c = input('Pct file exists, input "Y"/"y" to merge it or others to cancel deal:\n')
        if c == 'y' or c == 'Y':
            return None
    file = open(path, 'rb')
    text = file.read().decode('utf-8')
    file.close()
    l = text.splitlines()
    i = 0
    while i < len(l):
        x = l[i]
        nl = x.split('。')
        y = 0
        while y < len(nl):
            if nl[y].isspace() or nl[y] == '':
                del nl[y]
            else:
                nl[y] = pick(nl[y])
                y += 1
        l = l[:i] + nl + l[i+1:]
        i += len(nl)
    newf = open(path+'.pct', 'wb')
    for x in l:
        newf.write((x+'\n').encode('utf-8'))
    newf.flush()
    newf.close()
    return l


def generate(path, dictionary):
    if not os.path.exists(path+'.pct'):
        return
    file = open(path+'.pct', 'r', encoding='utf-8')
    text = file.read().splitlines()
    file.close()
    file = open(path+'.out', 'w', encoding='utf-8')
    r = ''
    for x in text:
        if x[:2] == '//':
            continue
        x = list(x)
        dic = {}
        i = 0
        ty = 'O'
        label = [None] * len(x)
        while i < len(x):
            if x[i] == '\\':
                del x[i]
                del label[i]
                # dictionary.add(x[i])
                label[i] = ty
                i += 1
            elif x[i] == '[':
                del x[i]
                del label[i]
                label[i] = 'B-PRI'
                ty = 'I-PRI'
                i += 1
            elif x[i] == ']':
                del x[i]
                del label[i]
                ty = 'O'
            elif x[i] == '{':
                del x[i]
                del label[i]
                label[i] = 'B-THP'
                ty = 'I-THP'
                i += 1
            elif x[i] == '}':
                del x[i]
                del label[i]
                ty = 'O'
            elif x[i] == '"':
                del x[i]
                del label[i]
                if ty == 'I-POS':
                    ty = 'O'
                else:
                    label[i] = 'B-POS'
                    ty = 'I-POS'
                    i += 1
            elif x[i] == "'":
                del x[i]
                del label[i]
                if ty == 'I-NEG':
                    ty = 'O'
                else:
                    label[i] = 'B-NEG'
                    ty = 'I-NEG'
                    i += 1
            else:
                # dictionary.add(x[i])
                label[i] = ty
                i += 1
        dic['text'] = x
        dic['label'] = label
        r += str(dic).replace("'", '"')+'\n'
        # file.write(str(dic)+'\n')
    if ty != 'O':
        print("Error, please check your pct file")
        return
    # dictionary.writeBack()
    file.write(r)
    file.close()


def h():
    print('Help')
    print('Command: open exit deal gen help')


def op():
    return input("Input the app number:\n")


# def writeConfig(users):
#     conf = open(userconf, 'w')
#     conf.write(repr(users))
#     conf.close()

# def adduser(users):
#     n = input("Input user name:\n")
#     if n in users:
#         print("Error: user exists")
#         return
#     users[n] = []
#     writeConfig(users)

def genall():
    l = os.listdir('.')
    for x in l:
        if 'app' in x and os.path.isdir(x):
            p = os.path.join(x, "p")
            if os.path.exists(os.path.join(x, "p.pct")):
                generate(p, dictionary)

# def loadapps():
#     f = open(appconf, 'r')
#     r = eval(f.read())
#     l = os.listdir('.')
#     modified = False
#     for x in l:
#         if 'app' in x and os.path.isdir:
#             name = x[3:]
#             if name not in r:
#                 modified = True
#                 r[name] = [None, 0]
#     f.close()
#     if modified:
#         f = open(appconf, 'w')
#         f.write(repr(r))
#         f.close()

# def login():
#     return ''
#     # return input("Input user name:\n")


# def loadusers():
#     conf = open(userconf, 'r')
#     r = eval(conf.read())
#     conf.close()
#     return r



dictionary = Dictionary()
# users = loadusers()
# apps = loadapps()
# user = login()
num = None
while True:
    # print(f"@{user}[" + ('None' if num is None else ('app' + num)) + "]$", end='')
    print(f"@[" + ('None' if num is None else ('app' + num)) + "]$", end='')
    s = input()
    if s == 'exit':
        break
    elif s == 'open':
        num = op()
    elif s == 'deal' or s == 'gen':
        if num is None:
            num = op()
        path = 'app' + num + '/p'
        if not os.path.exists(path):
            print('Error: file \'' + path + '\' not exist')
            continue
        if s == 'deal':
            deal(path)
        else:
            generate(path, dictionary)
    elif s == 'genall':
        genall()
    elif s == 'gendict':
        genDict(dictionary)
        dictionary.writeBack()
    elif s == 'help':
        h()
    # elif user == 'root':
    #     if s == 'adduser':
    #         # adduser(users)
    #         pass
    else:
        print("Error: unknow command.")
        h()

